package com.zqwh.storemonitor.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.zqwh.storemonitor.R;
import com.zqwh.storemonitor.domain.ShopBell;
import com.zqwh.storemonitor.ezviz.EZUtils;
import com.zqwh.storemonitor.model.WatcherModel;
import com.zqwh.yj.sdk.utils.DeviceUtils;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;
import com.zqwh.yj.sdk.widget.monindicator.MonIndicator;

import static com.zqwh.storemonitor.StoreMonitorApplication.getOpenSDK;
import static com.zqwh.storemonitor.StoreMonitorApplication.sSelectedCamera;
import static com.zqwh.storemonitor.StoreMonitorApplication.sSelectedShop;

public class CameraDetailActivity extends BaseActivity {
    private SurfaceView svRealplay;
    private ImageView imgSoundSwitch;
    private ImageView imgVoiceSwitch;
    private ImageView imgLockSwitch;

    private RelativeLayout rlMask;
    private RelativeLayout rlTalk;
    private ImageView imgCloseDialog;
    private TextView tvTalkTip;
    private MonIndicator miTalking;

    private EZPlayer ezPlayer;
    private WatcherModel watcherModel;
    private boolean isOutAllow = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_detail);
        watcherModel = new WatcherModel(this);
        setView();

        createPlayer();
        getOutAllow();
        setClickLisenter();
    }

    private void setView() {
        rlMask = findViewById(R.id.rl_mask);
        rlTalk = findViewById(R.id.rl_talk);
        imgCloseDialog = findViewById(R.id.img_close_dialog);
        tvTalkTip = findViewById(R.id.tv_talk_tip);
        miTalking = findViewById(R.id.mi_talking);

        svRealplay = findViewById(R.id.sv_realplay);
        imgSoundSwitch = findViewById(R.id.img_sound_switch);
        imgVoiceSwitch = findViewById(R.id.img_voice_switch);
        imgLockSwitch = findViewById(R.id.img_lock_switch);
    }

    private void getOutAllow() {
        watcherModel.getOutAllow(DeviceUtils.getSN(), new NetCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                isOutAllow = aBoolean;
                updateUI();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void setClickLisenter() {
        imgSoundSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sSelectedCamera.isMonitorSoundOn()){
                    if (ezPlayer != null) {
                        ezPlayer.closeSound();
                        sSelectedCamera.setMonitorSoundOn(false);
                        updateUI();
                    }
                }else {
                    if (ezPlayer != null) {
                        ezPlayer.openSound();
                        sSelectedCamera.setMonitorSoundOn(true);
                        updateUI();
                    }
                }
            }
        });
        imgVoiceSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ezPlayer != null) {
                    showTalkDialog();
                    ezPlayer.startVoiceTalk();
                    sSelectedCamera.setMonitorVoiceOn(true);
                    updateUI();
                }
            }
        });
        imgLockSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                watcherModel.setOutAllow(sSelectedShop.getDevSn(), !isOutAllow, new NetCallback<ShopBell>() {
                    @Override
                    public void onSuccess(ShopBell shopBell) {
                        isOutAllow = shopBell.isOutAllow();
                        updateUI();
                    }

                    @Override
                    public void onError(String msg) {
                        ToastUtils.showLongToast(CameraDetailActivity.this, "操作失败");
                    }
                });
            }
        });
        imgCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ezPlayer.stopVoiceTalk();
                hideTalkDialog();
                sSelectedCamera.setMonitorVoiceOn(false);
                updateUI();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startRealPlay();
            }
        }, 500);
    }

    private void createPlayer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EZDeviceInfo deviceInfo = null;
                try {
                    deviceInfo = getOpenSDK().getDeviceInfo(sSelectedCamera.getMonitorSn());
                    EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, sSelectedCamera.getIndex());
                    ezPlayer = getOpenSDK().createPlayer(cameraInfo.getDeviceSerial(), cameraInfo.getCameraNo());
                    ezPlayer.setSurfaceHold(svRealplay.getHolder());
                } catch (BaseException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void updateUI(){
        if (sSelectedCamera.isMonitorSoundOn()){
            imgSoundSwitch.setAlpha((float) 1);
        }else {
            imgSoundSwitch.setAlpha((float) 0.5);
        }

        if (sSelectedCamera.isMonitorVoiceOn()){
            imgVoiceSwitch.setAlpha((float) 1);
        }else {
            imgVoiceSwitch.setAlpha((float) 0.5);
        }

        if (isOutAllow){
            imgLockSwitch.setImageDrawable(getDrawable(R.mipmap.lock_on));
        }else {
            imgLockSwitch.setImageDrawable(getDrawable(R.mipmap.lock_off));
        }
    }

    private void startRealPlay() {
        ezPlayer.setHandler(new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_SUCCESS:
                        startTalkSuccess();
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_STOP:
                        LogUtils.logout("MSG_REALPLAY_VOICETALK_STOP");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_FAIL:
                        ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                        startTalkFail();
                        break;
                    case EZConstants.MSG_GOT_STREAM_TYPE:
                        LogUtils.logout("handleMessage -->" + "获取到当前取流类型");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                        //播放成功
                        LogUtils.logout("handleMessage -->" + "播放成功");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_STOP_SUCCESS:
                        //播放成功
                        LogUtils.logout("handleMessage -->" + "停止成功");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                        //播放失败,得到失败信息
                        ErrorInfo errorinfo = (ErrorInfo) msg.obj;
                        //得到播放失败错误码
                        int code = errorinfo.errorCode;
                        //得到播放失败模块错误码
                        String codeStr = errorinfo.moduleCode;
                        //得到播放失败描述
                        String description = errorinfo.description;
                        //得到播放失败解决方方案
                        String sulution = errorinfo.sulution;
                        LogUtils.logout("handleMessage -->播放失败,得到失败信息: " + errorinfo.toString());
                        break;
                    case EZConstants.MSG_VIDEO_SIZE_CHANGED:
                        //解析出视频画面分辨率回调
                        try {
                            String temp = (String) msg.obj;
                            String[] strings = temp.split(":");
                            int mVideoWidth = Integer.parseInt(strings[0]);
                            int mVideoHeight = Integer.parseInt(strings[1]);
                            //解析出视频分辨率
                            LogUtils.logout("handleMessage -->解析出视频分辨率: " + mVideoWidth + "," + mVideoHeight);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        }));
        ezPlayer.startRealPlay();
        ezPlayer.closeSound();
    }

    private void showTalkDialog() {
        rlMask.setVisibility(View.VISIBLE);
        rlTalk.setVisibility(View.VISIBLE);
        imgCloseDialog.setVisibility(View.VISIBLE);
        tvTalkTip.setVisibility(View.VISIBLE);
    }

    private void startTalkSuccess() {
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.VISIBLE);
    }

    private void startTalkFail() {
        tvTalkTip.setText("启动失败，点击重试");
    }

    private void hideTalkDialog() {
        rlMask.setVisibility(View.GONE);
        rlTalk.setVisibility(View.GONE);
        imgCloseDialog.setVisibility(View.GONE);
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ezPlayer != null) {
            ezPlayer.release();
        }
    }
}
